package com.sloera.jvm.ref;

import java.lang.ref.SoftReference;

/**
 * @author sloera
 * @create 2020/5/3
 */
public class SoftReferenceDemo {
    public static void softRefMemoryEnough() {
        Object object = new Object();
        SoftReference<Object> softReference = new SoftReference<>(object);
        System.out.println(object);
        System.out.println(softReference.get());

        object = null;
        System.gc();
        System.out.println(object);
        System.out.println(softReference.get());
    }

    /**
     * 配置-Xms5m -Xmx5m -XX:+PrintGCDetails使内存不足
     */
    public static void softRefMemoryNotEnough() {
        Object object = new Object();
        SoftReference<Object> softReference = new SoftReference<>(object);
        System.out.println(object);
        System.out.println(softReference.get());

        object = null;

        try {
            byte[] bytes = new byte[30 * 1024 * 1024];
        } finally {
            System.out.println(object);
            System.out.println(softReference.get());
        }
    }

    public static void main(String[] args) {
        //softRefMemoryEnough();
        softRefMemoryNotEnough();
    }
}
